<?php

namespace app\controller;

use app\BaseController;
use app\common\Snowflake;
use GuzzleHttp\Client;
use think\facade\Cache;
use think\facade\Db;
use think\Request;
use think\response\Json;
use GuzzleHttp\Exception\GuzzleException;

class Product extends BaseController
{

    //CREATE TABLE `game_product` (
    //`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    //`type` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '产品类型',
    //`name` varchar(64) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '产品名称',
    //`sub_name` varchar(64) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '副标题名称',
    //`header_image` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '产品头图URL',
    //`capsule_image` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '产品封面图URL',
    //`app_id` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '产品唯一标识ID',
    //`dir_name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '产品目录名称',
    //`archive_path` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '存档路径',
    //`order` int(11) DEFAULT NULL COMMENT '排序优先级',
    //`popularity` int(11) NOT NULL DEFAULT '0' COMMENT '产品热度值',
    //`rating` decimal(6,2) DEFAULT NULL COMMENT '产品评分',
    //`introduction` text COLLATE utf8mb4_unicode_ci COMMENT '产品介绍',
    //`description` text COLLATE utf8mb4_unicode_ci COMMENT '产品描述',
    //`keywords` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '关键字',
    //`is_published` tinyint(4) DEFAULT NULL COMMENT '是否已发布，0-未发布，1-已发布',
    //`game_video` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT '' COMMENT '游戏视频路径',
    //`release_date` datetime DEFAULT NULL COMMENT '发布时间',
    //`developer` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT '' COMMENT '开发者',
    //`publisher` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT '' COMMENT '发行商',
    //`created_at` datetime DEFAULT NULL COMMENT '创建时间',
    //`updated_at` datetime DEFAULT NULL COMMENT '更新时间',
    //`is_offline` tinyint(4) DEFAULT NULL COMMENT '是否已下线，0-未下线，1-已下线',
    //`website` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '产品官网地址',
    //PRIMARY KEY (`id`) USING BTREE,
    //UNIQUE KEY `game_product_app_id_unique` (`app_id`) USING BTREE,
    //KEY `game_product_type_index` (`type`) USING BTREE,
    //KEY `game_product_created_at_index` (`created_at`) USING BTREE,
    //KEY `idx_type_created_at` (`type`,`created_at`),
    //KEY `idx_published_order` (`is_published`,`order`),
    //KEY `idx_product_is_published` (`is_published`)
    //) ENGINE=InnoDB AUTO_INCREMENT=732545015435550817 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='游戏产品表，记录游戏的详细信息';
    //
    //CREATE TABLE `game_product_sku` (
    //`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    //`product_id` bigint(20) unsigned NOT NULL COMMENT '产品ID',
    //`old_price` decimal(20,2) unsigned NOT NULL COMMENT '原价',
    //`price` decimal(20,2) unsigned NOT NULL COMMENT '当前售价',
    //`discount` decimal(6,4) unsigned NOT NULL COMMENT '折扣比例',
    //`is_free` tinyint(4) NOT NULL COMMENT '是否免费，0-收费，1-免费',
    //`spec_info` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '规格信息-字符串',
    //`created_at` datetime DEFAULT NULL COMMENT '创建时间',
    //`updated_at` datetime DEFAULT NULL COMMENT '更新时间',
    //`specs` json DEFAULT NULL COMMENT '规格信息-json数组',
    //`introduction` text COLLATE utf8mb4_unicode_ci COMMENT '商品简介',
    //`service` text COLLATE utf8mb4_unicode_ci COMMENT '服务信息',
    //`sale` int(11) DEFAULT '0' COMMENT '销量',
    //PRIMARY KEY (`id`) USING BTREE,
    //KEY `game_product_sku_product_id_index` (`product_id`) USING BTREE,
    //KEY `idx_product_price` (`product_id`,`price`),
    //KEY `idx_product_sale` (`product_id`,`sale`),
    //KEY `idx_sku_product_price` (`product_id`,`price`),
    //KEY `idx_sku_product` (`product_id`)
    //) ENGINE=InnoDB AUTO_INCREMENT=732548278889275427 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='游戏产品SKU表，记录游戏的SKU及其价格信息';
    //
    //CREATE TABLE `game_product_feature` (
    //`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    //`product_id` bigint(20) unsigned NOT NULL COMMENT '产品ID',
    //`feature_id` bigint(20) unsigned NOT NULL COMMENT '特色ID',
    //`feature_name` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '特色名称',
    //`feature_image` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '特色图片URL',
    //`sort` int(11) NOT NULL DEFAULT '0' COMMENT '排序值（数值越小越靠前，默认0）',
    //`created_at` datetime DEFAULT NULL COMMENT '创建时间',
    //`updated_at` datetime DEFAULT NULL COMMENT '更新时间',
    //PRIMARY KEY (`id`) USING BTREE,
    //KEY `game_product_feature_product_id_index` (`product_id`) USING BTREE,
    //KEY `game_product_feature_feature_id_index` (`feature_id`) USING BTREE,
    //KEY `idx_feature_product` (`product_id`)
    //) ENGINE=InnoDB AUTO_INCREMENT=590 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='游戏产品特色表，记录产品与特色的关联信息';
    //
    //CREATE TABLE `game_product_category` (
    //`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    //`product_id` bigint(20) unsigned NOT NULL COMMENT '产品ID',
    //`category_id` bigint(20) unsigned NOT NULL COMMENT '分类ID',
    //`category_name` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '分类名称',
    //PRIMARY KEY (`id`) USING BTREE,
    //KEY `game_product_category_product_id_index` (`product_id`) USING BTREE,
    //KEY `game_product_category_category_id_index` (`category_id`) USING BTREE,
    //KEY `idx_category_product` (`product_id`)
    //) ENGINE=InnoDB AUTO_INCREMENT=387 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='游戏产品分类表，记录产品与分类的关联信息';
    //
    //CREATE TABLE `game_product_genre` (
    //`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    //`product_id` bigint(20) unsigned NOT NULL COMMENT '产品ID',
    //`genre_id` bigint(20) unsigned NOT NULL COMMENT '类型ID',
    //`genre_name` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '类型名称',
    //PRIMARY KEY (`id`) USING BTREE,
    //KEY `game_product_genre_product_id_index` (`product_id`) USING BTREE,
    //KEY `game_product_genre_genre_id_index` (`genre_id`) USING BTREE,
    //KEY `idx_genre_product` (`product_id`)
    //) ENGINE=InnoDB AUTO_INCREMENT=1373 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='游戏产品类型表，记录产品与类型的关联信息';
    //
    //CREATE TABLE `game_product_platform` (
    //`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    //`product_id` bigint(20) unsigned NOT NULL COMMENT '产品ID',
    //`name` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '平台名称',
    //`is_supported` tinyint(4) NOT NULL COMMENT '是否支持该平台，0-不支持，1-支持',
    //`minimum_requirement` text COLLATE utf8mb4_unicode_ci COMMENT '最低配置要求',
    //`recommended_requirement` text COLLATE utf8mb4_unicode_ci COMMENT '推荐配置要求',
    //PRIMARY KEY (`id`) USING BTREE,
    //KEY `game_product_platform_product_id_index` (`product_id`) USING BTREE,
    //KEY `game_product_platform_name_index` (`name`) USING BTREE,
    //KEY `idx_platform_product` (`product_id`)
    //) ENGINE=InnoDB AUTO_INCREMENT=1542 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='游戏产品平台表，记录游戏支持的平台及相关要求';
    //
    //CREATE TABLE `game_product_screenshot` (
    //`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    //`product_id` bigint(20) unsigned NOT NULL COMMENT '产品ID',
    //`type` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'unknown' COMMENT '截图类型',
    //`path` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '截图存储路径',
    //`arguments` json DEFAULT NULL COMMENT '截图参数',
    //PRIMARY KEY (`id`) USING BTREE,
    //KEY `game_product_screenshot_product_id_index` (`product_id`) USING BTREE,
    //KEY `idx_screenshot_product` (`product_id`)
    //) ENGINE=InnoDB AUTO_INCREMENT=9321 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='游戏截图表，记录游戏的截图及相关参数';


    //------------------------------------------------------图片处理------------------------------------------------------
    //删除图片 $url
    public function delFile($url): bool|string
    {
        try {
            $cosUploader = new CosUploader(config('basic.cos.bucket'), config('basic.cos.region'), config('basic.cos.secretId'), config('basic.cos.secretKey'));
            $res = $cosUploader->deleteFile($url);
            return $res;
        } catch (\Exception $e) {
            return "";
        }

    }

    //上传文件例子
    public function uploadFileExamples(Request $request): Json
    {
        try {
            $param = $request->param();
            $url = $param['url'] ?? "";
            $path = $param['path'] ?? "game/game/";
            $res = $this->uploadFile($url, $path);
            var_dump($res);
            die();

        } catch (\Exception $e) {
            var_dump($e->getMessage());
            return json(['code' => -1, 'msg' => '请求失败']);
        }
    }

    //图片要实时上传,图片上传到/game/game/里           视频要异步上传
    public function uploadFile($url, $path): string
    {
        try {
            $cosUploader = new CosUploader(config('basic.cos.bucket'), config('basic.cos.region'), config('basic.cos.secretId'), config('basic.cos.secretKey'));
            $res = $cosUploader->uploadFileFromUrl($url, $path);
            return '/' . $res['Key'];

        } catch (\Exception $e) {
            return "";
        }
    }


    //------------------------------------------------------产品处理------------------------------------------------------
    // 从Steam API获取游戏详情
    private function getSteamGameDetails(string $appId): array
    {
        try {
            $getAppUrl = "https://store.steampowered.com/api/appdetails/?appids=$appId&key=0&l=zh&format=json";
            $client = new Client();
            $response = $client->request('GET', $getAppUrl, [
                'headers' => [
                    'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
                ]
            ]);

            $body = $response->getBody();
            return json_decode($body, true);
        } catch (GuzzleException $e) {
            // 记录错误日志
            throw new \RuntimeException("获取Steam游戏详情失败");
        }
    }

    // 添加sku信息
    public function addProduct(Request $request): Json
    {
        try {

            // 清除产品列表相关的Redis缓存
            $this->clearProductCache();

            //开启事务
            Db::startTrans();

            //-------------------------------------------1.获取参数-------------------------------------------------------
            $param = $request->param();

            $app_id = $param['app_id'] ?? "";                 //app_id
            if (empty($app_id)) {
                return json(['code' => -1, 'msg' => 'APP ID不能为空']);
            }

            $is_published = $param['is_published'] ?? 0;      //是否已发布 0-未发布，1-已发布
            $name = $param['name'] ?? "";                     //游戏名称
            $features_ids = $param['features_ids'] ?? "";     //产品特性ids -> 不能为空
            if (empty($features_ids)) {
                return json(['code' => -1, 'msg' => '产品特征ids不能为空']);
            }
            $sub_name = $param['sub_name'] ?? "";             //副标题名称 -> 可以为空
            $categories_ids = $param['categories_ids'] ?? ""; //分类ids -> 可以为空

            //游戏类别genre_ids -> 可以为空
            $genre_ids = $param['genre_ids'] ?? "";           //游戏类别ids -> 可以为空

            //当有游戏类别时, 直接使用传过来的genre_ids, 否则使用app_id获取的genres
            $keywords = $param['keywords'] ?? "";             //关键字 -> 前端要传, 数据库没有字段, 可以为空
            //----------------------------
            $spec_info = $param['spec_info'] ?? "";           //版本  -> 不能为空
            if (empty($spec_info)) {
                return json(['code' => -1, 'msg' => '版本不能为空']);
            }
            //----------------------------
            $order = $param['order'] ?? 0;                    //排序优先级 -> 可以为空
            //----------------------------
            $old_price = $param['old_price'] ?? 0;            //原价     -> 不能为空
            if (empty($old_price)) {
                return json(['code' => -1, 'msg' => '原价不能为空']);
            }
            //----------------------------
            $rating = $param['rating'] ?? 0;                  //评分      -> 可以为空
            //----------------------------
            $price = $param['price'] ?? 0;                    //优惠价    -> 不能为空
            //----------------------------
            if (empty($price)) {
                return json(['code' => -1, 'msg' => '优惠价不能为空']);
            }
            if ($price > $old_price) {
                return json(['code' => -1, 'msg' => '优惠价不能大于原价']);  //优惠价要小于等于原价
            }
            //----------------------------
            $popularity = $param['popularity'] ?? 0;          //热度值    -> 可以为空

            $header_image = $param['header_image'] ?? "";     //缩略图（横） -> 可以为空
            $capsule_image = $param['capsule_image'] ?? "";   //缩略图（纵） -> 可以为空

            $dir_name = $param['dir_name'] ?? "";             //产品目录名称 -> 可以为空
            $archive_path = $param['archive_path'] ?? "";     //存档路径 -> 可以为空
            //$is_offline = $param['is_offline'] ?? 0;        //是否已下线 0-未下线，1-已下线 -> 暂时没用,可以为空

            $introduction = $param['introduction'] ?? "";     //产品介绍 -> 可以为空
            $description = $param['description'] ?? "";       //产品描述 -> 可以为空

            //最低配置
            $minimum_requirement = $param['minimum_requirement'] ?? "";             //最低配置 -> 可以为空
            //推荐配置
            $recommended_requirement = $param['recommended_requirement'] ?? "";     //推荐配置 -> 可以为空
            //游戏截图
            $screenshots = $param['screenshots'] ?? "";                             //游戏截图 -> 可以为空
            //游戏视频
            $game_video = $param['game_video'] ?? "";                               //游戏视频 -> 可以为空

            $release_date = $param['release_date'] ?? "";                         //发布时间 -> 可以为空
            $developer = $param['developer'] ?? "";                               //开发者 -> 可以为空
            $publisher = $param['publisher'] ?? "";                               //发行商 -> 可以为空

            //var_dump($release_date,$developer,$publisher);die;

            //游戏数据
            $app_data = $param['app_data'] ?? '';                                   //todo 此处待测试

            $snowflake = new Snowflake(1, 1);
            // -------------------------------------------2.查询app_id信息-----------------------------------------------
            $game_product = Db::name("game_product")->where("app_id", $app_id)->find();

            //如果找不到这个产品信息, 就要传app_data
            if (empty($game_product)) {

                // -------------------------------------------3.处理数据------------------------------------------------------
                if (empty($app_data)) {
                    return json(['code' => -1, 'msg' => '请填写app_data']);
                }


                if ($app_data[$app_id]['success'] == "true") {

                    $app_Data = $app_data[$app_id]['data'];

                    //todo 如果查询出来的产品信息为空, 则需要新增产品, 如果不为空, 就用这里的产品信息


                    //①.新增产品--------------------------------------------------------------------
                    $product_id = $snowflake->nextId();
                    $line['id'] = $product_id;
                    $line['type'] = $app_Data['type'] ?? "";        //产品类型
                    //----------------------------------------
                    if ($name == "") {
                        $line['name'] = $app_Data['name'] ?? "";    //产品名称
                    } else {
                        $line['name'] = $name;
                    }
                    //----------------------------------------
                    if ($sub_name == "") {                          //副标题名称
                        $line['sub_name'] = $app_Data['sub_name'] ?? "";
                    } else {
                        $line['sub_name'] = $sub_name;
                    }
                    //----------------------------------------
                    if ($header_image == "") {                      //产品头图URL
                        $line['header_image'] = $this->uploadFile($app_Data['header_image'] ?? "", "/game/game/") ?? "";     //todo header_image 这个地方上传到腾讯云cos
                    } else {
                        $line['header_image'] = $header_image;
                    }
                    //----------------------------------------
                    if ($capsule_image == "") {                     //产品封面图URL
                        $line['capsule_image'] = $this->uploadFile($app_Data['capsule_image'] ?? "", "/game/game/") ?? "";    //todo capsule_image 这个地方上传到腾讯云cos
                    } else {
                        $line['capsule_image'] = $capsule_image;
                    }
                    $line['app_id'] = $app_Data['steam_appid'] ?? "";   //产品唯一标识ID
                    $line['dir_name'] = $dir_name;                      //产品目录名称
                    $line['archive_path'] = $archive_path;              //存档路径
                    $line['order'] = $order;                            //排序优先级
                    $line['popularity'] = $popularity;                  //产品热度值
                    $line['rating'] = $rating;

                    //----------------------------------------
                    if ($introduction == "") {                          //产品介绍
                        $line['introduction'] = $app_Data['short_description'] ?? "";
                    } else {
                        $line['introduction'] = $introduction;
                    }
                    //----------------------------------------
                    if ($description == "") {                       //产品描述
                        $line['description'] = $app_Data['about_the_game'] ?? "";
                    } else {
                        $line['description'] = $description;
                    }
                    $line['keywords'] = $keywords;                 //关键字
                    $line['is_published'] = $is_published;         //是否已发布 0-未发布，1-已发布

                    //第一个视频
                    if ($game_video == "") {                        //todo game_video 这个地方需要使用定时任务上传到腾讯云cos
                        $line['game_video'] = $app_Data['movies'][0]['webm']['480'] ?? "";
                    }

                    if ($release_date){
                        $line['release_date'] = $release_date;                         //发布时间
                    } else {
                        //转换发布时间
                        $dateString = $app_Data['release_date']['date'] ?? '';
                        if (!empty($dateString)) {
                            // 将中文格式转换为标准格式（如 "2019 年 7 月 31 日" => "2019-07-31"）
                            $cleanDate = preg_replace('/\s*年\s*/', '-', $dateString);
                            $cleanDate = preg_replace('/\s*月\s*/', '-', $cleanDate);
                            $cleanDate = preg_replace('/\s*日\s*/', '', $cleanDate);

                            $timestamp = strtotime($cleanDate);
                            $line['release_date'] = ($timestamp !== false) ? date('Y-m-d H:i:s', $timestamp) : null;
                        } else {
                            $line['release_date'] = null;
                        }
                    }
                    if ($developer == "") {
                        $line['developer'] = implode(",", $app_Data['developers']?? []) ?? ""; //开发者
                    } else {
                        $line['developer'] = $developer;
                    }
                    if ($publisher == "") {
                        $line['publisher'] = implode(",", $app_Data['publishers']?? []) ?? ""; //发行商
                    } else {
                        $line['publisher'] = $publisher;
                    }
                    $line['created_at'] = date("Y-m-d H:i:s");
                    $line['updated_at'] = date("Y-m-d H:i:s");

                    $line['website'] = $app_Data['website'] ?? ""; //产品官网地址
                    $line['is_offline'] = $is_offline ?? "";       //是否已下线 0-未下线，1-已下线
                    $res = Db::name("game_product")->fetchSql(false)->insert($line);


                    // ④.新增游戏产品分类----------------------------------------------------------
                    $category_id_Arr = explode(",", rtrim($categories_ids, ","));
                    $category_info_Arr = Db::name("game_category")->where("id", "in", $category_id_Arr)->fetchSql(false)->select()->toArray();
                    if ($category_info_Arr) {
                        foreach ($category_info_Arr as $value) {
                            $game_category = Db::name("game_category")->where("id", $value['id'])->find();
                            if (!empty($game_category)) {
                                $game_product_category_line['product_id'] = $product_id;
                                $game_product_category_line['category_id'] = $game_category['id'];
                                $game_product_category_line['category_name'] = $game_category['name'];
                                Db::name("game_product_category")->fetchSql(false)->insert($game_product_category_line);
                            }
                        }
                    }

                    //⑤.新增游戏产品类别------------------------------------------------------------
                    if (empty($genre_ids)) {
                        $genres = $app_Data['genres'] ?? [];
                        if ($genres) {
                            foreach ($genres as $value) {
                                //如果$value['description'] 为 免费 或者 免费开玩, 则跳过
                                if ($value['description'] == "免费" || $value['description'] == "免费开玩") {
                                    continue;
                                }
                                $game_genre = Db::name("game_genre")->where("name", $value['description'])->find();
                                if (empty($game_genre)) {
                                    $game_genre_line['id'] = $snowflake->nextId();
                                    $game_genre_line['name'] = $value['description'];
                                    $game_genre_line['order'] = 0;
                                    $game_genre_line['created_at'] = date("Y-m-d H:i:s");
                                    $game_genre_line['updated_at'] = date("Y-m-d H:i:s");
                                    Db::name("game_genre")->fetchSql(false)->insert($game_genre_line);
                                }
                            }
                        }
                        // 存入game_product_genre表
                        if ($genres) {
                            foreach ($genres as $value) {
                                //如果$value['description'] 为 免费 或者 免费开玩, 则跳过
                                if ($value['description'] == "免费" || $value['description'] == "免费开玩") {
                                    continue;
                                }
                                $game_genre = Db::name("game_genre")->where("name", $value['description'])->find();
                                if (!empty($game_genre)) {
                                    $game_product_genre_line['product_id'] = $product_id;
                                    $game_product_genre_line['genre_id'] = $game_genre['id'];
                                    $game_product_genre_line['genre_name'] = $value['description'];
                                    Db::name("game_product_genre")->fetchSql(false)->insert($game_product_genre_line);
                                }
                            }
                        }
                    } else {
                        $genre_id_Arr = explode(",", rtrim($genre_ids, ","));
                        $genre_info_Arr = Db::name("game_genre")->where("id", "in", $genre_id_Arr)->fetchSql(false)->select()->toArray();
                        if ($genre_info_Arr) {
                            foreach ($genre_info_Arr as $value) {
                                $game_product_genre_line['product_id'] = $product_id;
                                $game_product_genre_line['genre_id'] = $value['id'];
                                $game_product_genre_line['genre_name'] = $value['name'];
                                Db::name("game_product_genre")->fetchSql(false)->insert($game_product_genre_line);
                            }
                        }
                    }


                    // ⑥.新增游戏产品平台------------------------------------------------------------
                    if (empty($minimum_requirement)) {
                        $minimum_requirement = $app_Data['pc_requirements']['minimum'] ?? "";
                    }
                    if (empty($recommended_requirement)) {
                        $recommended_requirement = $app_Data['pc_requirements']['recommended'] ?? "";
                    }
                    $platform_data = [
                        'product_id' => $product_id,
                        'name' => 'windows',
                        'is_supported' => 1,
                        'minimum_requirement' => $minimum_requirement,
                        'recommended_requirement' => $recommended_requirement,
                    ];
                    $res3 = Db::name("game_product_platform")->insert($platform_data);

                    // ⑦.新增游戏产品截图------------------------------------------------------------
                    $screenshot_data = [];
                    if ($screenshots) {
                        $screenshots_Arr1 = explode(",", $screenshots);
                        foreach ($screenshots_Arr1 as $value) {
                            $screenshot_data[] = [
                                'product_id' => $product_id,
                                'type' => 'IMAGE',
                                'path' => $value,
                                'arguments' => [],
                            ];
                        }
                    } else {
                        //如果没有传入截图, 则从Steam API获取, 然后将截图上传到腾讯云
                        $screenshots_Arr2 = $app_Data['screenshots'] ?? [];
                        $maxScreenshots = 10; // Maximum number of screenshots to process
                        $processedCount = 0;

                        foreach ($screenshots_Arr2 as $value) {
                            if ($processedCount >= $maxScreenshots) {
                                break; // Stop processing after 20 screenshots
                            }

                            $img_path = $this->uploadFile($value['path_full'] ?? "", "/game/game/") ?? "";
                            if (!empty($img_path)) {
                                $screenshot_data[] = [
                                    'product_id' => $product_id,
                                    'type' => 'IMAGE',
                                    'path' => $img_path,
                                    'arguments' => [],
                                ];
                                $processedCount++; // Increment counter only for successful uploads
                            }
                        }
                    }

                    if (!empty($screenshot_data ?? [])) {
                        $res4 = Db::name("game_product_screenshot")->fetchSql(false)->insertAll($screenshot_data);
                    } else {
                        $res4 = false;
                    }

                } else {
                    return json(['code' => -1, 'msg' => '获取Steam游戏详情失败']);
                }

            } else {

                $product_id = $game_product['id'];
            }


            //②. 新增游戏产品特征----------------------------------------------------------
            $feature_id_Arr = explode(",", rtrim($features_ids, ","));
            $feature_info_Arr = Db::name("game_feature")->where("id", "in", $feature_id_Arr)->fetchSql(false)->select()->toArray();
            if ($feature_info_Arr) {
                foreach ($feature_info_Arr as $value) {
                    $game_product_feature_line['product_id'] = $product_id;
                    $game_product_feature_line['feature_id'] = $value['id'];
                    $game_product_feature_line['feature_name'] = $value['name'];
                    $game_product_feature_line['feature_image'] = $value['image'];
                    $game_product_feature_line['sort'] = 0;
                    $game_product_feature_line['created_at'] = date("Y-m-d H:i:s");
                    $game_product_feature_line['updated_at'] = date("Y-m-d H:i:s");
                    Db::name("game_product_feature")->fetchSql(false)->insert($game_product_feature_line);
                }
            } else {
                return json(['code' => -1, 'msg' => '产品特性ids查不到']);
            }


            //③.新增产品sku-----------------------------------------------------------------
            $sku_id = $snowflake->nextId();
            $line2['id'] = $sku_id;
            $line2['product_id'] = $product_id;
            $line2['old_price'] = $old_price;
            $line2['price'] = $price;
            if ($price > 0) {
                $line2['discount'] = round(($price) / $old_price * 100, 2);
            } else {
                $line2['discount'] = 0;
            }
            // 根据特征判断是否有会员免费特性
            $is_free = 0;
            foreach ($feature_info_Arr as $value) {
                if ($value['name'] == "会员免费") {
                    $is_free = 1;
                    break;
                }
            }
            $line2['is_free'] = $is_free;
            $line2['spec_info'] = $spec_info;
            $line2['created_at'] = date("Y-m-d H:i:s");
            $line2['updated_at'] = date("Y-m-d H:i:s");

            $line2['specs'] = json_encode([]);
            $line2['introduction'] = "";
            $line2['service'] = "";
            $line2['sale'] = 0;
            Db::name("game_product_sku")->fetchSql(false)->insert($line2);

            //提交事务
            Db::commit();

            return json(['code' => 0, 'msg' => '添加成功', "data" => ['product_id' => $product_id, 'sku_id' => $sku_id]]);

        } catch (\Exception $e) {
            Db::rollback();
            var_dump($e->getMessage());
            return json(['code' => -1, 'msg' => '请求失败']);
        }
        //
    }

    // 删除sku_id信息
    public function delProduct(Request $request): Json
    {
        try {
            // 清除产品列表相关的Redis缓存
            $this->clearProductCache();

            $param = $request->param();
            $sku_id = $param['sku_id'] ?? "";
            //获取sku_id
            if (empty($sku_id)) {
                return json(['code' => -1, 'msg' => 'SKU ID不能为空']);
            }

            //查询game_product_sku表是否有这个sku_id
            $game_product_sku = Db::name("game_product_sku")->where("id", $sku_id)->find();
            if (empty($game_product_sku)) {
                return json(['code' => -1, 'msg' => 'SKU ID不存在']);
            }

            $product_id = $game_product_sku['product_id'];
            $sku_list = DB::name("game_product_sku")->where("product_id", $product_id)->select();
            $count = count($sku_list);

            Db::startTrans();

            if ($count > 1) {
                Db::name("game_product_sku")->where("id", $sku_id)->delete();
            } else {
                //删除产品表数据
                Db::name("game_product")->where("id", $game_product_sku['product_id'])->delete();
                //删除产品sku表数据
                Db::name("game_product_sku")->where("id", $sku_id)->delete();
                //删除产品特性表数据
                Db::name("game_product_feature")->where("product_id", $game_product_sku['product_id'])->delete();
                //删除产品分类表数据
                Db::name("game_product_category")->where("product_id", $game_product_sku['product_id'])->delete();
                //删除产品类型表数据
                Db::name("game_product_genre")->where("product_id", $game_product_sku['product_id'])->delete();
                //删除game_product_platform
                Db::name("game_product_platform")->where("product_id", $game_product_sku['product_id'])->delete();
                //删除game_product_screenshot
                Db::name("game_product_screenshot")->where("product_id", $game_product_sku['product_id'])->delete();
                //todo 删除账号

            }

            //提交事务
            Db::commit();
            return json(['code' => 0, 'msg' => '删除成功']);

        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => -1, 'msg' => '请求失败']);
        }
    }

    // 根据sku_id获取
    public function productDetail(Request $request): Json
    {
        try {
            $skuId = $request->param('sku_id');
            if (empty($skuId)) {
                return json(['code' => -1, 'msg' => 'SKU ID不能为空']);
            }

            // 查询SKU基础信息
            $skuInfo = Db::name('game_product_sku')
                ->field('id as sku_id, product_id, old_price, price, discount, 
                    is_free, spec_info, specs, introduction, service, sale')
                ->where('id', $skuId)
                ->find();
            if (empty($skuInfo)) {
                return json(['code' => -1, 'msg' => 'SKU不存在']);
            }

            // 查询产品主信息
            $productInfo = Db::name('game_product')
                ->field('id, type, name, sub_name, header_image, capsule_image, app_id,
                    dir_name,archive_path,website, order, popularity, rating, introduction,
                    description, keywords, is_published, is_offline, game_video,
                    release_date, developer, publisher, created_at, updated_at')
                ->where('id', $skuInfo['product_id'])
                ->find();

            // cdn处理
            $cdn = config('basic.cdn');
            //如果不为空, 并且没有https
            if (!empty($productInfo['header_image']) && !str_contains($productInfo['header_image'], 'https://')) {
                $productInfo['header_image'] = $cdn . $productInfo['header_image'];
            }
            //处理capsule_image
            if (!empty($productInfo['capsule_image']) && !str_contains($productInfo['capsule_image'], 'https://')) {
                $productInfo['capsule_image'] = $cdn . $productInfo['capsule_image'];
            }
            //处理game_video
            if (!empty($productInfo['game_video']) && !str_contains($productInfo['game_video'], 'https://')) {
                $productInfo['game_video'] = $cdn . $productInfo['game_video'];
            }


            // 查询关联特征信息（带排序）
            $features = Db::name('game_product_feature')
                ->field('feature_id, feature_name, feature_image, sort')
                ->where('product_id', $skuInfo['product_id'])
                ->order('sort', 'asc')
                ->select();

            // 查询分类信息（带分类ID）
            $categories = Db::name('game_product_category')
                ->field('category_id, category_name')
                ->where('product_id', $skuInfo['product_id'])
                ->select();

            // 查询类型信息（带类型ID）
            $genres = Db::name('game_product_genre')
                ->field('genre_id, genre_name')
                ->where('product_id', $skuInfo['product_id'])
                ->select();

            // 查询平台配置信息（带平台ID）
            $platforms = Db::name('game_product_platform')
                ->field('id as platform_id, name, is_supported, minimum_requirement, recommended_requirement')
                ->where('product_id', $skuInfo['product_id'])
                ->select();

            // 查询截图信息（带截图ID）
            $screenshots = Db::name('game_product_screenshot')
                ->field('id as screenshot_id, type, path, arguments')
                ->where('product_id', $skuInfo['product_id'])
                ->select();

            // 查询规格信息（新增规格数据）
            $specs = Db::name('game_product_spec')
                ->alias('s')
                ->join('game_product_spec_value v', 's.id = v.spec_id')
                ->field('s.id as spec_id, s.name as spec_name, 
                    v.id as spec_value_id, v.name as spec_value')
                ->where('s.product_id', $skuInfo['product_id'])
                ->select();


            // 数据结构重组
            $result = [
                'product' => array_merge($productInfo, [
                    'product_id' => strval($productInfo['id']),
                    'is_published' => (bool)$productInfo['is_published'],
                    'is_offline' => (bool)$productInfo['is_offline']
                ]),
                'sku' => array_merge($skuInfo, [
                    'specs' => json_decode($skuInfo['specs'], true) ?? [],
                    'is_free' => (bool)$skuInfo['is_free']
                ]),


                'features' => $features->map(function ($item) {
                    //处理feature_image
                    if (!empty($item['feature_image']) && !str_contains($item['feature_image'], 'https://')) {
                        $item['feature_image'] = config('basic.cdn') . $item['feature_image'];
                    }

                    return [
                        'feature_id' => strval($item['feature_id']),
                        'name' => $item['feature_name'],
                        'image' => $item['feature_image'],
                        'sort' => $item['sort']
                    ];
                }),
                'categories' => $categories->map(function ($item) {
                    return [
                        'category_id' => strval($item['category_id']),
                        'name' => $item['category_name']
                    ];
                }),


                'genres' => $genres->map(function ($item) {
                    return [
                        'genre_id' => strval($item['genre_id']),
                        'name' => $item['genre_name']
                    ];
                }),
                'platforms' => $platforms->map(function ($item) {
                    return [
                        'platform_id' => strval($item['platform_id']),
                        'name' => $item['name'],
                        'is_supported' => (bool)$item['is_supported'],
                        'requirements' => [
                            'minimum' => $item['minimum_requirement'],
                            'recommended' => $item['recommended_requirement']
                        ]
                    ];
                }),
                'media' => [
                    'screenshots' => $screenshots->map(function ($item) {

                        //处理path
                        if (!empty($item['path']) && !str_contains($item['path'], 'https://')) {
                            $item['path'] = config('basic.cdn') . $item['path'];
                        }

                        return [
                            'screenshot_id' => $item['screenshot_id'],
                            'type' => $item['type'],
                            'path' => $item['path'],
                            'arguments' => json_decode($item['arguments'], true)
                        ];
                    }),
                    //处理game_video
                    'game_video' => $productInfo['game_video']
                ]
            ];

            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $result
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => -1,
                'msg' => '获取详情失败: ' . $e->getMessage(),
                'trace' => config('app_debug') ? $e->getTrace() : []
            ]);
        }
    }

    // 根据sku_id修改信息
    public function editProduct(Request $request): Json
    {
        try {
            // 清除产品列表相关的Redis缓存
            //var_dump(111);die();
            $this->clearProductCache();

            // 开启事务
            Db::startTrans();

            // 获取参数
            $param = $request->param();

            // 检查sku_id是否存在
            $sku_id = $param['sku_id'] ?? "";
            if (empty($sku_id)) {
                return json(['code' => -1, 'msg' => 'SKU ID不能为空']);
            }

            // 查询游戏产品SKU
            $game_product_sku = Db::name("game_product_sku")->alias("s")
                ->field("s.*,p.app_id")
                ->leftJoin("game_product p", "s.product_id = p.id")
                ->where("s.id", $sku_id)
                ->find();
            if (empty($game_product_sku)) {
                return json(['code' => -1, 'msg' => 'SKU ID不存在']);
            }
            //处理APP_DATA
            $app_id = $game_product_sku['app_id'] ?? 1;
            $app_data = $param['app_data'][$app_id]['data'] ?? [];
            $product_id = $game_product_sku['product_id'];

            // 获取参数
            $is_published = $param['is_published'] ?? null;      // 是否已发布 0-未发布，1-已发布
            $name = $param['name'] ?? null;                      // 游戏名称
            $sub_name = $param['sub_name'] ?? null;              // 副标题名称
            $features_ids = $param['features_ids'] ?? "";        // 产品特性ids
            $categories_ids = $param['categories_ids'] ?? "";    // 分类ids

            $genre_ids = $param['genre_ids'] ?? "";              // 游戏类别ids
            $keywords = $param['keywords'] ?? null;              // 关键字
            $spec_info = $param['spec_info'] ?? null;            // 版本
            $order = $param['order'] ?? null;                    // 排序优先级
            $old_price = $param['old_price'] ?? null;            // 原价
            $price = $param['price'] ?? null;                    // 优惠价
            $rating = $param['rating'] ?? null;                  // 评分
            $popularity = $param['popularity'] ?? null;          // 热度值

            $header_image = $param['header_image'] ?? null;      // 缩略图（横）
            if (!empty($header_image) && str_contains($header_image, 'https://file.spacetime2024.online')) {
                $header_image = str_replace("https://file.spacetime2024.online", "", $header_image);
            }
            $capsule_image = $param['capsule_image'] ?? null;    // 缩略图（纵）
            if (!empty($capsule_image) && str_contains($capsule_image, 'https://file.spacetime2024.online')) {
                $capsule_image = str_replace("https://file.spacetime2024.online", "", $capsule_image);
            }

            $dir_name = $param['dir_name'] ?? null;              // 产品目录名称
            $archive_path = $param['archive_path'] ?? null;      // 存档路径
            //$is_offline = $param['is_offline'] ?? null;        // 是否已下线 0-未下线，1-已下线
            $introduction = $param['introduction'] ?? null;      // 产品介绍
            $description = $param['description'] ?? null;        // 产品描述

            $minimum_requirement = $param['minimum_requirement'] ?? null;         // 最低配置
            $recommended_requirement = $param['recommended_requirement'] ?? null; // 推荐配置

            $screenshots = $param['screenshots'] ?? "";                           // 游戏截图
            $game_video = $param['game_video'] ?? null;                           // 游戏视频

            $release_date = $param['release_date'] ?? "";                         //发布时间 -> 可以为空
            $developer = $param['developer'] ?? "";                               //开发者 -> 可以为空
            $publisher = $param['publisher'] ?? "";                               //发行商 -> 可以为空

            //处理$game_video里面的
            if (!empty($game_video) && str_contains($game_video, 'https://file.spacetime2024.online')) {
                $game_video = str_replace("https://file.spacetime2024.online", "", $game_video);
            }

            // 验证价格
            if ($price != null && $old_price != null && $price > $old_price) {
                return json(['code' => -1, 'msg' => '优惠价不能大于原价']);
            }

            // 更新产品基本信息--------------------------------------------------------------------------------------------
            $product_update = [];
            if ($is_published != null) $product_update['is_published'] = $is_published;    // 是否已发布 0-未发布，1-已发布
            if ($name != null) {
                $product_update['name'] = $name;
            } else {
                $product_update['name'] = $app_data['name'] ?? "";
            }
            if ($sub_name != null) {
                $product_update['sub_name'] = $sub_name;
            } else {
                $product_update['sub_name'] = $app_data['sub_name'] ?? "";
            }
            if ($keywords != null) $product_update['keywords'] = $keywords;                // 关键词
            if ($order != null) $product_update['order'] = $order;                         // 排序优先级
            if ($rating != null) $product_update['rating'] = $rating;                      // 评分
            if ($popularity != null) $product_update['popularity'] = $popularity;          // 人气
            if ($header_image != null) {
                $product_update['header_image'] = $header_image;
            } else {
                $product_update['header_image'] = $this->uploadFile($app_data['header_image'] ?? "", "/game/game/") ?? "";     //App_data header_image 这个地方上传到腾讯云cos
            }
            if ($capsule_image != null) {
                $product_update['capsule_image'] = $capsule_image;
            } else {
                $product_update['capsule_image'] = $this->uploadFile($app_data['capsule_image'] ?? "", "/game/game/") ?? "";    //App_data capsule_image 这个地方上传到腾讯云cos
            }
            if ($dir_name != null) $product_update['dir_name'] = $dir_name;
            if ($archive_path != null) $product_update['archive_path'] = $archive_path;
            //if ($is_offline !== null) $product_update['is_offline'] = $is_offline;
            if ($introduction != null) {
                $product_update['introduction'] = $introduction;
            } else {
                $product_update['introduction'] = $app_data['short_description'] ?? "";
            }
            if ($description != null) {
                $product_update['description'] = $description;
            } else {
                $product_update['description'] = $app_data['about_the_game'] ?? "";
            }
            if ($game_video != null) {
                $product_update['game_video'] = $game_video;
            } else {
                $product_update['game_video'] = $app_data['movies'][0]['webm']['480'] ?? "";
            }
            //if ($website !== null) $product_update['website'] = $website;
            //if ($developer !== null) $product_update['developer'] = $developer;
            //if ($publisher !== null) $product_update['publisher'] = $publisher;
            //if ($release_date !== null) $product_update['release_date'] = $release_date;


            if ($release_date){
                $product_update['release_date'] = $release_date;                         //发布时间
            } else {
                //转换发布时间
                $dateString = $app_data['release_date']['date'] ?? '';
                if (!empty($dateString)) {
                    // 将中文格式转换为标准格式（如 "2019 年 7 月 31 日" => "2019-07-31"）
                    $cleanDate = preg_replace('/\s*年\s*/', '-', $dateString);
                    $cleanDate = preg_replace('/\s*月\s*/', '-', $cleanDate);
                    $cleanDate = preg_replace('/\s*日\s*/', '', $cleanDate);

                    $timestamp = strtotime($cleanDate);
                    $product_update['release_date'] = ($timestamp !== false) ? date('Y-m-d H:i:s', $timestamp) : null;
                } else {
                    $product_update['release_date'] = null;
                }
            }
            if ($developer == "") {
                $product_update['developer'] = implode(",", $app_data['developers']?? []) ?? ""; //开发者
            } else {
                $product_update['developer'] = $developer;
            }
            if ($publisher == "") {
                $product_update['publisher'] = implode(",", $app_data['publishers'] ?? []) ?? ""; //发行商
            } else {
                $product_update['publisher'] = $publisher;
            }

            if (!empty($product_update)) {
                $product_update['updated_at'] = date("Y-m-d H:i:s");
                $res1 = Db::name("game_product")->where("id", $product_id)->fetchSql(false)->update($product_update);
            }

            // var_dump($res1);die;

            // 更新SKU信息-----------------------------------------------------------------------------------------------
            $sku_update = [];
            if ($old_price != null) $sku_update['old_price'] = $old_price;
            if ($price != null) {
                $sku_update['price'] = $price;
                if ($price > 0 && $old_price > 0) {
                    $sku_update['discount'] = round(($price) / $old_price * 100, 2);
                }
            }
            if ($spec_info != null) $sku_update['spec_info'] = $spec_info;

            if (!empty($sku_update)) {
                $sku_update['updated_at'] = date("Y-m-d H:i:s");
                $res2 = Db::name("game_product_sku")->where("id", $sku_id)->fetchSql(false)->update($sku_update);
            }


            //var_dump($features_ids);die();
            // 更新产品特征-----------------------------------------------------------------------------------------------
            if (!empty($features_ids)) {
                // 删除原有特征
                Db::name("game_product_feature")->where("product_id", $product_id)->delete();

                // 添加新特征
                $feature_id_Arr = explode(",", rtrim($features_ids, ","));
                $feature_info_Arr = Db::name("game_feature")->where("id", "in", $feature_id_Arr)->select()->toArray();


                if ($feature_info_Arr) {
                    foreach ($feature_info_Arr as $value) {
                        $game_product_feature_line = [
                            'product_id' => $product_id,
                            'feature_id' => $value['id'],
                            'feature_name' => $value['name'],
                            'feature_image' => $value['image'],
                            'sort' => 0,
                            'created_at' => date("Y-m-d H:i:s"),
                            'updated_at' => date("Y-m-d H:i:s")
                        ];
                        $res3 = Db::name("game_product_feature")->insert($game_product_feature_line);
                    }

                    // 检查是否有会员免费特性并更新SKU的is_free字段
                    $is_free = 0;
                    foreach ($feature_info_Arr as $value) {
                        if ($value['name'] == "会员免费") {
                            $is_free = 1;
                            break;
                        }
                    }
                    $res4 = Db::name("game_product_sku")->where("product_id", $product_id)->fetchSql(false)->update(['is_free' => $is_free]);
                }
            }

            // 更新分类信息----------------------------------可通过app_data获取分类------------------------------------------
            if (!empty($categories_ids)) {
                // 删除原有分类
                Db::name("game_product_category")->where("product_id", $product_id)->delete();

                // 添加新分类
                $category_id_Arr = explode(",", rtrim($categories_ids, ","));
                $category_info_Arr = Db::name("game_category")->where("id", "in", $category_id_Arr)->select()->toArray();

                if ($category_info_Arr) {
                    foreach ($category_info_Arr as $value) {
                        $game_product_category_line = [
                            'product_id' => $product_id,
                            'category_id' => $value['id'],
                            'category_name' => $value['name']
                        ];
                        Db::name("game_product_category")->insert($game_product_category_line);
                    }
                }
            }

            // 更新游戏类别----------------------------------可通过app_data获取类别-------------------------------------------
            if (!empty($genre_ids)) {
                // 删除原有类别
                Db::name("game_product_genre")->where("product_id", $product_id)->delete();

                // 添加新类别
                $genre_id_Arr = explode(",", rtrim($genre_ids, ","));
                $genre_info_Arr = Db::name("game_genre")->where("id", "in", $genre_id_Arr)->select()->toArray();

                if ($genre_info_Arr) {
                    foreach ($genre_info_Arr as $value) {
                        $game_product_genre_line = [
                            'product_id' => $product_id,
                            'genre_id' => $value['id'],
                            'genre_name' => $value['name']
                        ];
                        Db::name("game_product_genre")->insert($game_product_genre_line);
                    }
                }
            } else {
                Db::name("game_product_genre")->where("product_id", $product_id)->delete();

                $snowflake = new Snowflake(1, 1);
                $genres = $app_data['genres'] ?? [];
                if ($genres) {
                    foreach ($genres as $value) {
                        //如果$value['description'] 为 免费 或者 免费开玩, 则跳过
                        if ($value['description'] == "免费" || $value['description'] == "免费开玩") {
                            continue;
                        }
                        $game_genre = Db::name("game_genre")->where("name", $value['description'])->find();
                        //var_dump($value['description']);
                        if (empty($game_genre)) {
                            $game_genre_line['id'] = $snowflake->nextId();
                            $game_genre_line['name'] = $value['description'];
                            $game_genre_line['order'] = 0;
                            $game_genre_line['created_at'] = date("Y-m-d H:i:s");
                            $game_genre_line['updated_at'] = date("Y-m-d H:i:s");
                            Db::name("game_genre")->fetchSql(false)->insert($game_genre_line);
                        }
                    }
                }
                // 存入game_product_genre表
                if ($genres) {
                    foreach ($genres as $value) {
                        //如果$value['description'] 为 免费 或者 免费开玩, 则跳过
                        if ($value['description'] == "免费" || $value['description'] == "免费开玩") {
                            continue;
                        }
                        $game_genre = Db::name("game_genre")->where("name", $value['description'])->find();
                        if (!empty($game_genre)) {
                            $game_product_genre_line['product_id'] = $product_id;
                            $game_product_genre_line['genre_id'] = $game_genre['id'];
                            $game_product_genre_line['genre_name'] = $value['description'];
                            Db::name("game_product_genre")->fetchSql(false)->insert($game_product_genre_line);
                        }
                    }
                }
            }


            // 更新平台信息-----------------------------------------------------------------------------------------------
            // if ($minimum_requirement !== null || $recommended_requirement !== null) {
            $platform_update = [];
            if ($minimum_requirement != null) {
                $platform_update['minimum_requirement'] = $minimum_requirement;
            } else {
                $platform_update['minimum_requirement'] = $app_data['pc_requirements']['minimum'] ?? "";
            }
            if ($recommended_requirement != null) {
                $platform_update['recommended_requirement'] = $recommended_requirement;
            } else {
                $platform_update['recommended_requirement'] = $app_data['pc_requirements']['recommended'] ?? "";
            }

            if (!empty($platform_update)) {
                Db::name("game_product_platform")->where("product_id", $product_id)->where("name", 'windows')->update($platform_update);
            }
            // }

            // 更新游戏截图-----------------------------------------------------------------------------------------------
            if (!empty($screenshots)) {

                // 删除原有截图
                Db::name("game_product_screenshot")->where("product_id", $product_id)->delete();
                $screenshots_Arr = explode(",", $screenshots);
                $screenshot_data = [];

                foreach ($screenshots_Arr as $value) {

                    if (str_contains($value, 'https://file.spacetime2024.online')) {
                        $value = str_replace("https://file.spacetime2024.online", "", $value);
                    }

                    //删除桶里面的图片-> 不需要删除桶里的图片, 否则之前有的还需要重新上传一遍
                    //$this->delFile($value);

                    $screenshot_data[] = [
                        'product_id' => $product_id,
                        'type' => 'IMAGE',
                        'path' => $value,
                        'arguments' => json_encode([]),
                    ];
                }

                if (!empty($screenshot_data)) {
                    Db::name("game_product_screenshot")->insertAll($screenshot_data);
                }
            }

            // 提交事务
            Db::commit();
            return json(['code' => 0, 'msg' => '修改成功']);

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => -1, 'msg' => '修改失败：' . $e->getMessage()]);
        }
    }

    // sku列表
    public function productList(Request $request): Json
    {

        try {
            //var_dump(111);die;
            $param = $request->param();

            $page = $param['page'] ?? 1;
            $limit = $param['limit'] ?? 10;


            $map = [];

            //游戏名称    app_id    产品特征id     发布状态
            $name = $param['name'] ?? "";
            if (!empty($name)) {
                $map[] = ['p.name', 'like', "%$name%"];
            }
            $app_id = $param['app_id'] ?? "";
            if (!empty($app_id)) {
                $map[] = ['p.app_id', 'like', "%$app_id%"];
            }

            //产品特征id------------------------------
            $featureIds = $param['featureIds'] ?? "";
            if ($featureIds) {
                $featureIds_Arr = explode(",", $featureIds);
                $productIds = Db::name('game_product_feature')
                    ->where('feature_id', 'in', $featureIds_Arr)
                    ->column('product_id');
                if (!empty($productIds)) {
                    $map[] = ['p.id', 'in', $productIds];
                }
            }

            //发布状态-----------------------------------
            $is_published = $param['is_published'] ?? "";
            if ($is_published !== "") {
                $map[] = ['p.is_published', '=', $is_published];
            }

           //`release_date` datetime DEFAULT NULL COMMENT '发布时间',
           //`developer` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT '' COMMENT '开发者',
           //`publisher` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT '' COMMENT '发行商',

            //关联查询列表 以game_product_sku为主, 关联查询出game_product表信息, 字段别重复
            $dataObj = Db::name('game_product_sku')->alias('sku')
                ->leftJoin('game_product p', 'sku.product_id = p.id')
                ->field('sku.*,
                         p.name as product_name, p.app_id, p.sub_name as product_sub_name, p.is_published,
                         p.header_image as product_header_image, p.capsule_image as product_capsule_image, p.release_date as release_date, p.developer as developer, p.publisher as publisher,
                          (SELECT COUNT(*) FROM game_account WHERE sku_id = sku.id) as account_count,
                          (SELECT COUNT(*) FROM game_account WHERE sku_id = sku.id and status = "FREE") as account_FREE
                          '
                )
                ->where($map)
                ->order('sku.created_at', 'desc')
                ->page($page, $limit)
                ->select();

            $count = Db::name('game_product_sku')->alias('sku')
                ->leftJoin('game_product p', 'sku.product_id = p.id')
                ->field('sku.*,
                         p.name as product_name, p.app_id, p.sub_name as product_sub_name, p.is_published,
                         p.header_image as product_header_image, p.capsule_image as product_capsule_image'
                )
                ->where($map)
                ->order('sku.created_at', 'desc')
                ->count();

            //我需要把id 和 product_id 转成str, 给前端, 因为会出现精度丢失
            $dataArr = $dataObj->toArray();
            foreach ($dataArr as $key => $value) {
                $dataArr[$key]['id'] = (string)$value['id'];    //转成string
                $dataArr[$key]['product_id'] = (string)$value['product_id']; //转成string


                $dataArr[$key]['account_count_FREE'] = $dataArr[$key]['account_count'] . '/' . $dataArr[$key]['account_FREE'];

                //处理product_header_image cdn
                if (!empty($value['product_header_image']) && !str_contains($value['product_header_image'], 'https://')) {
                    $dataArr[$key]['product_header_image'] = config('basic.cdn') . $value['product_header_image'];
                }
                //处理product_capsule_image cdn
                if (!empty($value['product_capsule_image']) && !str_contains($value['product_capsule_image'], 'https://')) {
                    $dataArr[$key]['product_capsule_image'] = config('basic.cdn') . $value['product_capsule_image'];
                }

                //产品特征--------------------------------------------------
                $features = Db::name('game_product_feature')
                    ->field('feature_id, feature_name, feature_image')
                    ->where('product_id', $value['product_id'])
                    ->order('sort', 'asc')
                    ->select();

                $dataArr[$key]['features'] = $features->map(function ($item) {
                    //处理 feature_image cdn
                    if (!empty($item['feature_image']) && !str_contains($item['feature_image'], 'https://')) {
                        $item['feature_image'] = config('basic.cdn') . $item['feature_image'];
                    }

                    return [
                        'feature_id' => $item['feature_id'],
                        'name' => $item['feature_name'],
                        'image' => $item['feature_image']
                    ];
                });

                //产品分类--------------------------------------------------
                $categories = Db::name('game_product_category')
                    ->field('category_id, category_name')
                    ->where('product_id', $value['product_id'])
                    ->select();
                $dataArr[$key]['categories'] = $categories->map(function ($item) {
                    return [
                        'category_id' => $item['category_id'],
                        'name' => $item['category_name']
                    ];
                });

            }

            return json(['code' => 0, 'msg' => 'success', 'data' => ['list' => $dataArr, 'count' => $count]]);

        } catch (\Exception $e) {
            var_dump($e->getMessage());
            return json(['code' => -1, 'msg' => '服务繁忙,请稍后再试']);
        }
    }

    // 修改sku的发布状态
    public function editProductStatus(Request $request): Json
    {
        try {
            $param = $request->param();
            $sku_id = $param['sku_id'] ?? "";
            if (empty($sku_id)) {
                return json(['code' => -1, 'msg' => 'SKU ID不能为空']);
            }

            //查询game_product_sku表是否有这个sku_id
            $game_product_sku = Db::name("game_product_sku")->where("id", $sku_id)->find();
            if (empty($game_product_sku)) {
                return json(['code' => -1, 'msg' => 'SKU ID不存在']);
            }

            //开启事务
            Db::startTrans();

            //修改产品表的发布状态
            $is_published = $param['is_published'] ?? null;
            if ($is_published != null) {
                Db::name("game_product")->where("id", $game_product_sku['product_id'])->update(['is_published' => $is_published]);
            }

            //提交事务
            Db::commit();
            return json(['code' => 0, 'msg' => '修改成功']);

        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => -1, 'msg' => '请求失败']);
        }
    }


    //------------------------------------------------------账号相关------------------------------------------------------
    // 根据app_id获取获取product_id和sku_id
    public function getProductIdByAppId(Request $request): Json
    {
        try {
            $app_id = $request->param('app_id');
            if (empty($app_id)) {
                return json(['code' => -1, 'msg' => 'APP ID不能为空']);
            }

            // 查询产品信息
            $productInfo = Db::name('game_product')
                ->alias('p')
                ->leftJoin('game_product_sku sku', 'p.id = sku.product_id')
                ->field('p.id as product_id, sku.id as sku_id, p.name, p.app_id')
                ->where('app_id', $app_id)
                ->find();

            //根据sku_id 分组查询有多少spec_info
            $spec_info = Db::name('game_product_sku')
                ->field('id,spec_info')
                ->fetchSql(false)
                ->where('product_id', $productInfo['product_id'])
                //->group('spec_info')
                ->select()->toArray();
            //将spec_info id转成字符串
            foreach ($spec_info as $key => $value) {
                $spec_info[$key]['id'] = strval($value['id']);
            }
            $productInfo['spec_info'] = $spec_info;
            //将product_id  和 sku_id 转成string
            $productInfo['product_id'] = strval($productInfo['product_id']);
            $productInfo['sku_id'] = strval($productInfo['sku_id']);

            if ($productInfo) {
                return json(['code' => 0, 'msg' => 'success', 'data' => $productInfo]);
            } else {
                return json(['code' => -1, 'msg' => 'APP ID不存在']);
            }
        } catch (\Exception $e) {
            var_dump($e->getMessage());
            return json(['code' => -1, 'msg' => '请求失败']);
        }
    }

//CREATE TABLE `game_account` (
//`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
//`product_id` bigint(20) unsigned NOT NULL COMMENT '产品ID',
//`sku_id` bigint(20) unsigned NOT NULL COMMENT 'SKU ID',
//`account` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '游戏账号',
//`password` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '游戏账号密码',
//`description` varchar(128) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '描述信息',
//`status` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '账号状态',
//`remote_status` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '远程状态',
//`created_at` datetime DEFAULT NULL COMMENT '创建时间',
//`updated_at` datetime DEFAULT NULL COMMENT '更新时间',
//`account_type` tinyint(1) DEFAULT '1' COMMENT '账号类型: 1.临时登陆  2.一直在线   默认为1',
//PRIMARY KEY (`id`) USING BTREE,
//KEY `game_account_product_id_index` (`product_id`) USING BTREE,
//KEY `game_account_sku_id_index` (`sku_id`) USING BTREE,
//KEY `game_account_account_index` (`account`) USING BTREE,
//KEY `game_account_status_index` (`status`) USING BTREE,
//KEY `game_account_remote_status_index` (`remote_status`) USING BTREE
//) ENGINE=InnoDB AUTO_INCREMENT=732979155851112455 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='游戏账号表，记录游戏账号的基本信息和状态';

    // 添加账号
    public function addAccount(Request $request): Json
    {
        try {

            $param = $request->param();
            //var_dump($param);die;
            $snowflake = new Snowflake(1, 1);
            //添加账号
            $data = [
                //id是生成的
                "id" => $snowflake->nextId(),
                'product_id' => $param['product_id'],
                'sku_id' => $param['sku_id'],
                'account' => $param['account'],
                'password' => $param['password'],                          //只有下发账号的时候才有加密, 后台的增删改查不需要

                'description' => NULL,
                'status' => 'FREE',
                'remote_status' => 'NORMAL',
                'created_at' => date("Y-m-d H:i:s"),
                'updated_at' => date("Y-m-d H:i:s"),
                'account_type' => $param['account_type'] ?? 1              //账号类型: 1.临时登陆  2.一直在线   默认为1
            ];
            Db::name('game_account')->insert($data);

            return json(['code' => 0, 'msg' => '添加成功']);
        } catch (\Exception $e) {
            var_dump($e->getMessage());
            return json(['code' => -1, 'msg' => '请求失败']);
        }
    }

    // 账号列表
    public function accountList(Request $request): Json
    {
        try {

            $param = $request->param();
            $page = $param['page'] ?? 1;
            $limit = $param['limit'] ?? 10;

            //查询账号表
            $map = [];
            $product_id = $param['product_id'] ?? "";
            if (!empty($product_id)) {
                $map[] = ['product_id', '=', $product_id];
            }
            $sku_id = $param['sku_id'] ?? "";
            if (!empty($sku_id)) {
                $map[] = ['sku_id', '=', $sku_id];
            }
            $account = $param['account'] ?? "";
            if (!empty($account)) {
                $map[] = ['account', 'like', "%$account%"];
            }
            $app_id = $param['app_id'] ?? "";
            if (!empty($app_id)) {
                $map[] = ['p.app_id', 'like', "%$app_id%"];
            }
            $spec_info = $param['spec_info'] ?? "";
            if (!empty($spec_info)) {
                $map[] = ['sku.spec_info', 'like', "%$spec_info%"];
            }
            //产品名称
            $product_name = $param['product_name'] ?? "";
            if (!empty($product_name)) {
                $map[] = ['p.name', 'like', "%$product_name%"];
            }
            //状态
            $status = $param['status'] ?? "";
            if (!empty($status)) {
                $map[] = ['a.status', '=', $status];
            }
            //查账号表 需要关联查询出app_id, spec_info
            $dataObj = Db::name('game_account')->alias('a')
                ->leftJoin('game_product_sku sku', 'a.sku_id = sku.id')
                ->leftJoin('game_product p', 'sku.product_id = p.id')
                ->field('a.*, sku.spec_info, p.app_id, p.name as product_name, sku.product_id, sku.id as sku_id')
                ->where($map)
                ->order('a.created_at', 'desc')
                ->page($page, $limit)
                ->select();
            $count = Db::name('game_account')->alias('a')
                ->leftJoin('game_product_sku sku', 'a.sku_id = sku.id')
                ->leftJoin('game_product p', 'sku.product_id = p.id')
                ->field('a.*, sku.spec_info, p.app_id, p.name as product_name, sku.product_id, sku.id as sku_id')
                ->where($map)
                ->order('a.created_at', 'desc')
                ->count();

            $dataArr = $dataObj->toArray();
            //我需要把id 和 product_id 转成str, 给前端, 因为会出现精度丢失
            foreach ($dataArr as $key => $value) {
                $dataArr[$key]['id'] = strval($value['id']);
                $dataArr[$key]['product_id'] = strval($value['product_id']);
                $dataArr[$key]['sku_id'] = strval($value['sku_id']);
            }

            return json(['code' => 0, 'msg' => 'success', 'data' => ['list' => $dataArr, 'count' => $count]]);

        } catch (\Exception $e) {
            var_dump($e->getMessage());
            return json(['code' => -1, 'msg' => '请求失败']);
        }
    }

    // 修改账号
    public function editAccount(Request $request): Json
    {
        try {
            $param = $request->param();
            //var_dump($param);die;
            $id = $param['id'] ?? "";
            if (empty($id)) {
                return json(['code' => -1, 'msg' => 'ID不能为空']);
            }

            //查询game_account表是否有这个id
            $game_account = Db::name("game_account")->where("id", $id)->find();

            if (empty($game_account)) {
                return json(['code' => -1, 'msg' => 'id不存在']);
            }

            //开启事务
            Db::startTrans();

            //修改账号表数据
            $data = [
                'product_id' => $param['product_id'],
                'sku_id' => $param['sku_id'],
                'account' => $param['account'],
                'password' => $param['password'],                        //只有下发账号的时候才有加密, 后台的增删改查不需要

                'description' => NULL,
                'status' => 'FREE',
                'remote_status' => 'NORMAL',
                'updated_at' => date("Y-m-d H:i:s"),
                'account_type' => $param['account_type'] ?? 1            //账号类型: 1.临时登陆  2.一直在线   默认为1

            ];

            Db::name("game_account")->where("id", $id)->fetchSql(false)->update($data);

            //提交事务
            Db::commit();
            return json(['code' => 0, 'msg' => '修改成功']);

        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => -1, 'msg' => '请求失败']);
        }
    }

    // 删除账号
    public function delAccount(Request $request): Json
    {
        try {
            $id = $request->param('id');
            if (empty($id)) {
                return json(['code' => -1, 'msg' => 'ID不能为空']);
            }

            $game_account = Db::name("game_account")->where("id", $id)->find();
            if (empty($game_account)) {
                return json(['code' => -1, 'msg' => 'ID不存在']);
            }
            Db::name("game_account")->where("id", $id)->delete();
            return json(['code' => 0, 'msg' => '删除成功']);

        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => -1, 'msg' => '请求失败']);
        }
    }


    //------------------------------------------------------页签分类 增删改查----------------------------------------------

    /**
     * 添加游戏分类
     * @param Request $request
     * @return Json
     */
    public function addCategory(Request $request): Json
    {
        try {
            $param = $request->param();

            $name = $param['name'] ?? "";
            $order = $param['order'] ?? 0;

            if (empty($name)) {
                return json(['code' => -1, 'msg' => '分类名称不能为空']);
            }

            // 检查分类名称是否已存在
            $exists = Db::name('game_category')->where('name', $name)->find();
            if ($exists) {
                return json(['code' => -1, 'msg' => '分类名称已存在']);
            }

            $snowflake = new Snowflake(1, 1);
            $data = [
                'id' => $snowflake->nextId(),
                'name' => $name,
                'order' => $order,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ];

            Db::name('game_category')->insert($data);
            return json(['code' => 0, 'msg' => '添加成功', 'data' => ['id' => (string)$data['id']]]);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '添加失败：' . $e->getMessage()]);
        }
    }

    /**
     * 游戏分类列表
     * @param Request $request
     * @return Json
     */
    public function categoryList(Request $request): Json
    {
        try {
            $param = $request->param();
            $id = $param['id'] ?? '';
            $name = $param['name'] ?? '';
            $page = $param['page'] ?? 1;
            $limit = $param['limit'] ?? 10;

            $map = [];
            if (!empty($id)) {
                $map[] = ['id', '=', $id];
            }
            if (!empty($name)) {
                $map[] = ['name', 'like', "%$name%"];
            }

            $list = Db::name('game_category')
                ->where($map)
                ->order('order', 'asc')
                ->order('id', 'asc')
                ->page($page, $limit)
                ->select()->toArray();

            $count = Db::name('game_category')
                ->where($map)
                ->count();

            // 转换ID为字符串
            foreach ($list as $key => $value) {
                $list[$key]['id'] = strval($value['id']);
            }

            return json(['code' => 0, 'msg' => 'success', 'data' => ['list' => $list, 'count' => $count]]);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '获取列表失败：' . $e->getMessage()]);
        }
    }

    /**
     * 修改游戏分类
     * @param Request $request
     * @return Json
     */
    public function editCategory(Request $request): Json
    {
        try {
            $param = $request->param();
            $id = $param['id'] ?? "";
            $name = $param['name'] ?? "";
            $order = $param['order'] ?? null;

            if (empty($id)) {
                return json(['code' => -1, 'msg' => '分类ID不能为空']);
            }

            if (empty($name)) {
                return json(['code' => -1, 'msg' => '分类名称不能为空']);
            }

            // 检查分类是否存在
            $category = Db::name('game_category')->where('id', $id)->find();
            if (!$category) {
                return json(['code' => -1, 'msg' => '分类不存在']);
            }

            // 检查名称是否被其他分类使用
            $existsName = Db::name('game_category')->where('name', $name)->where('id', '<>', $id)->find();
            if ($existsName) {
                return json(['code' => -1, 'msg' => '分类名称已存在']);
            }

            $data = [
                'name' => $name,
                'updated_at' => date('Y-m-d H:i:s')
            ];

            if ($order !== null) {
                $data['order'] = $order;
            }

            Db::name('game_category')->where('id', $id)->update($data);
            return json(['code' => 0, 'msg' => '修改成功']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '修改失败：' . $e->getMessage()]);
        }
    }

    /**
     * 删除游戏分类
     * @param Request $request
     * @return Json
     */
    public function deleteCategory(Request $request): Json
    {
        try {
            $id = $request->param('id');

            if (empty($id)) {
                return json(['code' => -1, 'msg' => '分类ID不能为空']);
            }

            // 检查分类是否存在
            $category = Db::name('game_category')->where('id', $id)->find();
            if (!$category) {
                return json(['code' => -1, 'msg' => '分类不存在']);
            }

            //CREATE TABLE `game_product_category` (
            //`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
            //  `product_id` bigint(20) unsigned NOT NULL COMMENT '产品ID',
            //  `category_id` bigint(20) unsigned NOT NULL COMMENT '分类ID',
            //  `category_name` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '分类名称',
            //  PRIMARY KEY (`id`) USING BTREE,
            //  KEY `game_product_category_product_id_index` (`product_id`) USING BTREE,
            //  KEY `game_product_category_category_id_index` (`category_id`) USING BTREE,
            //  KEY `idx_category_product` (`product_id`)
            //) ENGINE=InnoDB AUTO_INCREMENT=978 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='游戏产品分类表，记录产品与分类的关联信息';

            // 检查分类是否被产品使用
            //$used = Db::name('game_product_category')->where('category_id', $id)->find();
            //if ($used) {
            //删除分类前先删除产品分类关联
            Db::name('game_product_category')->where('category_id', $id)->delete();
            // }

            Db::name('game_category')->where('id', $id)->delete();
            return json(['code' => 0, 'msg' => '删除成功']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '删除失败：' . $e->getMessage()]);
        }
    }


    //------------------------------------------------------产品特性 增删改查----------------------------------------------

    /**
     * 添加产品特性
     * @param Request $request
     * @return Json
     */
    public function addFeature(Request $request): Json
    {
        try {
            $param = $request->param();
            $name = $param['name'] ?? "";
            $image = $param['image'] ?? "";
            $sort = $param['sort'] ?? 0;

            if (empty($name)) {
                return json(['code' => -1, 'msg' => '特性名称不能为空']);
            }

            // 检查特性名称是否已存在
            $exists = Db::name('game_feature')->where('name', $name)->find();
            if ($exists) {
                return json(['code' => -1, 'msg' => '特性名称已存在']);
            }

            $snowflake = new Snowflake(1, 1);
            $data = [
                'id' => $snowflake->nextId(),
                'name' => $name,
                'image' => $image,
                'sort' => $sort,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ];

            Db::name('game_feature')->insert($data);
            return json(['code' => 0, 'msg' => '添加成功', 'data' => ['id' => (string)$data['id']]]);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '添加失败：' . $e->getMessage()]);
        }
    }

    /**
     * 产品特性列表
     * @param Request $request
     * @return Json
     */
    public function featureList(Request $request): Json
    {
        try {
            $param = $request->param();
            $id = $param['id'] ?? '';
            $page = $param['page'] ?? 1;
            $limit = $param['limit'] ?? 10;
            $name = $param['name'] ?? '';

            $map = [];
            if (!empty($id)) {
                $map[] = ['id', '=', $id];
            }
            if (!empty($name)) {
                $map[] = ['name', 'like', "%$name%"];
            }

            $list = Db::name('game_feature')
                ->where($map)
                ->order('sort', 'asc')
                ->order('id', 'asc')
                ->page($page, $limit)
                ->select()
                ->toArray();

            $count = Db::name('game_feature')
                ->where($map)
                ->count();

            // 转换ID为字符串，处理图片CDN
            foreach ($list as $key => $value) {
                $list[$key]['id'] = strval($value['id']);
                $list[$key]['image'] = config('basic.cdn') . $value['image'];
            }

            return json(['code' => 0, 'msg' => 'success', 'data' => ['list' => $list, 'count' => $count]]);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '获取列表失败：' . $e->getMessage()]);
        }
    }

    /**
     * 修改产品特性
     * @param Request $request
     * @return Json
     */
    public function editFeature(Request $request): Json
    {
        try {
            $param = $request->param();
            $id = $param['id'] ?? "";
            $name = $param['name'] ?? "";
            $image = $param['image'] ?? null;
            $sort = $param['sort'] ?? null;

            if (empty($id)) {
                return json(['code' => -1, 'msg' => '特性ID不能为空']);
            }

            if (empty($name)) {
                return json(['code' => -1, 'msg' => '特性名称不能为空']);
            }

            // 检查特性是否存在
            $feature = Db::name('game_feature')->where('id', $id)->find();
            if (!$feature) {
                return json(['code' => -1, 'msg' => '特性不存在']);
            }

            // 检查名称是否被其他特性使用
            $existsName = Db::name('game_feature')->where('name', $name)->where('id', '<>', $id)->find();
            if ($existsName) {
                return json(['code' => -1, 'msg' => '特性名称已存在']);
            }

            $data = [
                'name' => $name,
                'updated_at' => date('Y-m-d H:i:s')
            ];

            if ($image !== null) {
                // 处理图片URL，去除域名前缀
                if (str_contains($image, 'https://file.spacetime2024.online')) {
                    $image = str_replace("https://file.spacetime2024.online", "", $image);
                }
                $data['image'] = $image;
            }

            if ($sort !== null) {
                $data['sort'] = $sort;
            }

            Db::name('game_feature')->where('id', $id)->update($data);

            // 同步更新所有使用此特性的产品中的特性名称和图片
            $updateData = [
                'feature_name' => $name,
                'updated_at' => date('Y-m-d H:i:s')
            ];

            if ($image !== null) {
                $updateData['feature_image'] = $image;
            }

            Db::name('game_product_feature')->where('feature_id', $id)->update($updateData);

            return json(['code' => 0, 'msg' => '修改成功']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '修改失败：' . $e->getMessage()]);
        }
    }

    /**
     * 删除产品特性
     * @param Request $request
     * @return Json
     */
    public function deleteFeature(Request $request): Json
    {
        try {
            $id = $request->param('id');

            if (empty($id)) {
                return json(['code' => -1, 'msg' => '特性ID不能为空']);
            }

            // 检查特性是否存在
            $feature = Db::name('game_feature')->where('id', $id)->find();
            if (!$feature) {
                return json(['code' => -1, 'msg' => '特性不存在']);
            }

            // 检查特性是否被产品使用
            $used = Db::name('game_product_feature')->where('feature_id', $id)->find();
            if ($used) {
                return json(['code' => -1, 'msg' => '该特性已被产品使用，不能删除']);
            }

            Db::name('game_feature')->where('id', $id)->delete();
            return json(['code' => 0, 'msg' => '删除成功']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '删除失败：' . $e->getMessage()]);
        }
    }


    //------------------------------------------------------游戏类型 增删改查----------------------------------------------

    /**
     * 添加游戏类型
     * @param Request $request
     * @return Json
     */
    public function addGenre(Request $request): Json
    {
        try {
            $param = $request->param();
            $name = $param['name'] ?? "";
            $order = $param['order'] ?? 0;

            if (empty($name)) {
                return json(['code' => -1, 'msg' => '类型名称不能为空']);
            }

            // 检查类型名称是否已存在
            $exists = Db::name('game_genre')->where('name', $name)->find();
            if ($exists) {
                return json(['code' => -1, 'msg' => '类型名称已存在']);
            }

            $snowflake = new Snowflake(1, 1);
            $data = [
                'id' => $snowflake->nextId(),
                'name' => $name,
                'order' => $order,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ];

            Db::name('game_genre')->insert($data);
            return json(['code' => 0, 'msg' => '添加成功', 'data' => ['id' => (string)$data['id']]]);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '添加失败：' . $e->getMessage()]);
        }
    }

    /**
     * 游戏类型列表
     * @param Request $request
     * @return Json
     */
    public function genreList(Request $request): Json
    {
        try {
            $param = $request->param();
            $id = $param['id'] ?? '';
            $page = $param['page'] ?? 1;
            $limit = $param['limit'] ?? 10;
            $name = $param['name'] ?? '';

            $map = [];
            if (!empty($id)) {
                $map[] = ['id', '=', $id];
            }
            if (!empty($name)) {
                $map[] = ['name', 'like', "%$name%"];
            }

            $list = Db::name('game_genre')
                ->where($map)
                ->order('order', 'asc')
                ->order('id', 'asc')
                ->page($page, $limit)
                ->select()
                ->toArray();

            $count = Db::name('game_genre')
                ->where($map)
                ->count();

            // 转换ID为字符串
            foreach ($list as $key => $value) {
                $list[$key]['id'] = strval($value['id']);
            }


            return json(['code' => 0, 'msg' => 'success', 'data' => ['list' => $list, 'count' => $count]]);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '获取列表失败：' . $e->getMessage()]);
        }
    }

    /**
     * 修改游戏类型
     * @param Request $request
     * @return Json
     */
    public function editGenre(Request $request): Json
    {
        try {
            $param = $request->param();
            $id = $param['id'] ?? "";
            $name = $param['name'] ?? "";
            $order = $param['order'] ?? null;

            if (empty($id)) {
                return json(['code' => -1, 'msg' => '类型ID不能为空']);
            }

            if (empty($name)) {
                return json(['code' => -1, 'msg' => '类型名称不能为空']);
            }

            // 检查类型是否存在
            $genre = Db::name('game_genre')->where('id', $id)->find();
            if (!$genre) {
                return json(['code' => -1, 'msg' => '类型不存在']);
            }

            // 检查名称是否被其他类型使用
            $existsName = Db::name('game_genre')->where('name', $name)->where('id', '<>', $id)->find();
            if ($existsName) {
                return json(['code' => -1, 'msg' => '类型名称已存在']);
            }

            $data = [
                'name' => $name,
                'updated_at' => date('Y-m-d H:i:s')
            ];

            if ($order !== null) {
                $data['order'] = $order;
            }

            Db::name('game_genre')->where('id', $id)->update($data);


            return json(['code' => 0, 'msg' => '修改成功']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '修改失败：' . $e->getMessage()]);
        }
    }

    /**
     * 删除游戏类型
     * @param Request $request
     * @return Json
     */
    public function deleteGenre(Request $request): Json
    {
        try {
            $id = $request->param('id');

            if (empty($id)) {
                return json(['code' => -1, 'msg' => '类型ID不能为空']);
            }

            // 检查类型是否存在
            $genre = Db::name('game_genre')->where('id', $id)->find();
            if (!$genre) {
                return json(['code' => -1, 'msg' => '类型不存在']);
            }

            // 检查类型是否被产品使用
            $used = Db::name('game_product_genre')->where('genre_id', $id)->find();
            if ($used) {
                return json(['code' => -1, 'msg' => '该类型已被产品使用，不能删除']);
            }

            Db::name('game_genre')->where('id', $id)->delete();
            return json(['code' => 0, 'msg' => '删除成功']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * 清除产品列表相关缓存
     * @return bool 是否成功清除缓存
     */
    protected function clearProductCache(): bool
    {
        try {
            $redis = Cache::store('redis_01');
            $keys = $redis->keys('*game:product:list*');
            if (!empty($keys)) {
                // 批量删除所有匹配的键, 可以删除数组
                $redis->del($keys);
            }

            return true;
        } catch (\Exception $e) {
            // 处理异常
            //echo '清除缓存失败：' . $e->getMessage();
            return false;
        }
    }

}